<?php

declare(strict_types=1);

namespace cosy\framework\command\curd;

use cosy\framework\command\BaseMake;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

/**
 * ClassName Controller
 * Description TODO
 * Author BTC
 * Date 2023/11/3 19:35
 **/
class Controller extends BaseMake
{
    protected $type = 'controller';

    protected function configure()
    {
        $this->setName('cosy:controller')
            ->addArgument('module', Argument::REQUIRED, 'Please input your class name')
            ->addArgument('table', Argument::REQUIRED, 'Please input your table name')
            ->setDescription('创建一个controller控制器');
    }

    protected function execute(Input $input, Output $output)
    {
        $table = trim($input->getArgument('table'));
        $tableName = substr($table, strlen(env('DB_PREFIX')));
        $array = explode('_', $tableName);
        foreach ($array as $key => $val){
            $array[$key] = ucfirst($val);
        }
        $mapper = implode('', $array);

        $module = trim($input->getArgument('module'));
        $name = 'app\\' . $module . '\\' . $this->type . '\\' . $mapper;

        $classname = $this->getClassName($name);

        $pathname = $this->getPathName($classname);

        if (is_file($pathname)) {
            $output->writeln('<error>' . $this->type . ':' . $classname . ' already exists!</error>');
            return false;
        }

        if (!is_dir(dirname($pathname))) {
            mkdir(dirname($pathname), 0755, true);
        }

        file_put_contents($pathname, $this->buildClass($classname));

        $output->writeln('<info>' . $this->type . ':' . $classname . ' created successfully.</info>');
    }
    // 填充模板
    public function buildClass($name)
    {
        $stub = $this->getStub();
        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');

        $class = str_replace($namespace . '\\', '', $name);

        $serviceName = $class . 'Service';
        $validateName = $class . 'Validate';
        if(config('route.controller_suffix') == true){
            $controllerName = $class.'Controller';
        }else{
            $controllerName = $class;
        }

        $namespaceDirName = substr($namespace, 0, strrpos($namespace, '\\'));

        $search = [
            '{%createTime%}',
            '{%validateNameSpace%}',
            '{%className%}',
            '{%lowerClassName%}',
            '{%namespace%}',
            '{%controllerName%}',
            '{%serviceNameSpace%}',
            '{%serviceName%}',
        ];

        $replace = [
            date('Y-m-d H:i'),
            $namespaceDirName.'\validate' . DIRECTORY_SEPARATOR . $validateName,
            $class,
            lcfirst($class),
            $namespace,
            $controllerName,
            $namespaceDirName . '\service'. DIRECTORY_SEPARATOR . $serviceName,
            $class . 'Service'
        ];
        return str_replace($search, $replace, $stub);
    }

    /**
     * 获取模板
     * @return string
     */
    protected function getStub()
    {
        $path = __DIR__.DIRECTORY_SEPARATOR.'stubs'.DIRECTORY_SEPARATOR.$this->type.'.stub';
        return file_get_contents($path);
    }

    protected function getClassName(string $name): string
    {
        if (strpos($name, '\\') !== false) {
            return $name;
        }

        if (strpos($name, '@')) {
            [$app, $name] = explode('@', $name);
        } else {
            $app = '';
        }

        if (strpos($name, '/') !== false) {
            $name = str_replace('/', '\\', $name);
        }

        return $this->getNamespace($app) . '\\' . $name;
    }

    protected function getPathName(string $name): string
    {
        $name = str_replace('app\\', '', $name);
        if(config('route.controller_suffix') == true){
            $name = $name.'Controller';
        }
        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
    }
}